package com.lfx.concurrent;

import java.time.LocalDateTime;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolExecutorMain {

    public static void main(String[] args) {
        scheduleWithFixedDelay();
//        scheduleAtFixedRate();
    }

    /**
     * 与任务执行时间无关，任务执行时间必须小于间隔时间,否则执行间隔时间就是上次任务执行时间
     */
    private static void scheduleAtFixedRate(){

        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(5);
        scheduledThreadPoolExecutor.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                LocalDateTime now = LocalDateTime.now();
                System.out.println("执行时间:"+now);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },4,3, TimeUnit.SECONDS);
    }


    /**
     * 与任务时间有关，间隔时间等于固定间隔时间+任务执行时间
     */
    private static void scheduleWithFixedDelay(){
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(4);
        scheduledThreadPoolExecutor.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                LocalDateTime now = LocalDateTime.now();
                System.out.println("执行时间:"+now);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },4,7,TimeUnit.SECONDS);
    }


}
